<template>
  <el-container class="user_container flex">
    <Aside @handleNodeClick="handleNodeClick" />
    <el-main class="user_main flex-1">
      <Breadcrumb :title="pageTitle" />
      <div class="user_content flex main_content">
        <el-form ref="searchMap" :inline="true" :model="searchMap" class="serach_wrapper flex-space-between">
          <div class="search">
            <el-form-item prop="labelId" size="small">
              <el-select v-model="searchMap.labelId" placeholder="请选择用户组">
                <el-option v-for="option in labelIdArr" :key="option.value" :label="option.label" :value="option.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="projectPointName" size="small">
              <el-input v-model="searchMap.projectPointName" placeholder="用户组名称"></el-input>
            </el-form-item>
            <el-form-item class="flex">
              <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
              <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
            </el-form-item>
          </div>
          <div class="edit">
            <el-form-item class="flex">
              <el-button @click="tagAdd()" class="btn_cancel" icon="el-icon-plus">
                用户组管理
              </el-button>
            </el-form-item>
            <el-form-item class="flex">
              <el-button @click="handleAdd()" class="btn_primary" icon="el-icon-plus">
                新增
              </el-button>
            </el-form-item>
          </div>

        </el-form>
        <!-- 表格 -->
        <transition name="fade">
          <el-table :data="contactList" stripe class="per_table" style="width: 100%" height="250" v-loading="loading">
            <el-table-column type="index" prop="userId" label="序号"></el-table-column>
            <!-- <el-table-column prop="addressBookAccount" label="用户账号"></el-table-column> -->
            <el-table-column prop="addressBookName" label="用户名称"></el-table-column>
            <!-- <el-table-column prop="addressBookName" label="姓名 "></el-table-column>
            <el-table-column prop="phonenumber" label="联系电话"></el-table-column> -->
            <el-table-column key="status" label="所属用户组">
              <template slot-scope="scope">
                <div class="flex-box" v-if="scope.row.labelName && scope.row.labelName.split(',').length > 1">
                  <el-tag type="success">{{ scope.row.labelName ? scope.row.labelName.split(',')[0] : '' }}</el-tag>
                  <el-tooltip class="item" effect="dark" placement="top-start">
                    <div slot="content">{{ scope.row.labelName }}</div>
                    <el-tag type="success">...</el-tag>
                  </el-tooltip>
                </div>
                <div class="flex-box" v-else-if="scope.row.labelName && scope.row.labelName.split(',').length == 1">
                  <el-tag type="success">{{ scope.row.labelName }}</el-tag>
                </div>
                <div class="flex-box" v-else>
                  <el-tag type="success">暂无数据</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <div class="button-group">
                  <span type="text" class="tag_primary" size="small" @click="handleEdit(scope.row, 'edit')">编辑</span>
                  <span type="text" class="tag_warning" size="small" @click="handleDelete(scope.row, 'delete')">删除</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </transition>
        <div class="content_footer">
          <el-pagination v-show="total > 0" :total="total" :page-sizes="[10, 20]" @current-change="contactList" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" :page-size="searchMap.pageSize" layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </div>
      </div>
    </el-main>

    <!-- 弹窗 - 新增/编辑 start -->
    <div class="dialog_content">
      <el-dialog class="m_dialog" :title="title" :visible.sync="DialogVisibleUser" width="800" append-to-body :close-on-click-modal="false">
        <div class="content">
          <custom-form ref="addUserFrom" :formModel="formModel" :formItemConfig="formItemConfig" :formRules="formRules" label-width="80px" label-position="left">
            <template #tempName>
              <el-checkbox-group v-model="formModel.labelList">
                <el-checkbox v-for="item in labelIdArr" :label="item.value" :key="item.value">{{ item.label }}</el-checkbox>
                <div style="display: inline-block;">
                  <span class="checkbox-icon iconfontShuzhi icon-jia"></span>
                  <span class="checkbox-title" @click="tagAdd()">增加用户组</span>
                </div>
              </el-checkbox-group>
            </template>
          </custom-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="DialogVisibleUser = false" class="btn_cancel">取 消</el-button>
          <el-button type="primary" @click="submitFrom('addUserFrom')" class="btn_primary">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 弹窗 - 新增/编辑 end -->
    <!-- 标签管理弹窗 start -->
    <TagManagementTable :tableDialogVisible="tableDialogVisible" @cancel="cancel" @getLabelList="initgetLabelList"></TagManagementTable>
    <!-- 标签管理弹窗 end -->

  </el-container>
</template>
<script>
import Aside from '@/components/Aside'
import Breadcrumb from '@/components/Breadcrumb'

import TagManagementTable from './TagManagementTable.vue'
import { EventBus } from '@/utils/eventbus'
import { addContacts, updateContacts, delContacts, getLabelList, getContactsId, getContactsList, listUser } from '@/api'
export default {
  name: 'personnel',
  components: {
    Aside,
    Breadcrumb,
    TagManagementTable
  },
  data () {
    return {
      title: "用户组管理",
      // 标签管理弹窗
      tableDialogVisible: false,
      dataState: 0,
      // 遮罩层
      loading: true,
      // 通讯录列表
      contactList: [],
      // 通讯录人员标签
      contactTag: [],
      // 岗位选项
      personnelOptions: [],
      // 总条数
      total: 0,
      // 搜索参数
      searchMap: {
        pageNum: 1, // 当前页
        pageSize: 10,  // 默认条数
        // 标签id
        labelId: undefined,
        // 搜索框
        keyword: undefined,
        // 项目id
        deptId: undefined,
        // 项目名称
        projectPointName: undefined,
        projectPointId: undefined
      },
      // 弹出框状态
      DialogVisibleUser: false,
      // 标签弹窗状态
      tagManagement: false,
      // 项目名称下拉框
      // projectPointName:[],
      // 角色名称
      labelIdArr: [],
      // 提交表单数据
      formModel: {
        // 用户ID集合
        userIdList: [],
        // 标签编码
        remark: null,
        //标签数组
        labelList: [],
      },
      // tempData: [{"createBy":"admin","createTime":"2024-04-07 17:51:03","updateBy":"admin","updateTime":"2024-04-07 17:51:03","remark":null,"labelId":"1776910551014866946","labelCode":"1001","labelName":"值班人员","delFlag":"0"},{"createBy":"admin","createTime":"2024-04-07 17:51:39","updateBy":"admin","updateTime":"2024-04-07 17:51:39","remark":null,"labelId":"1776910700973817857","labelCode":"1002","labelName":"安全管理人员","delFlag":"0"}],
      // 表单配置项
      formItemConfig: [
        {
          label: '项目点名称',
          prop: 'projectPointName',
          component: 'BaseSelect',
          span: 12,
          disabled: true,
          clearable: true,
          width: '100%',
          options: [],
        },
        {
          label: '用户姓名',
          prop: 'userIdList',
          component: 'BaseMultipleSelect',
          span: 12,
          clearable: true,
          width: '100%',
        },
        {
          label: '备注',
          prop: 'remark',
          row: 4,
          type: 'textarea',
          span: 24,
          width: '100%',
        },
        {
          label: '用户组名称',
          prop: 'labelList',
          row: 4,
          slotName: 'tempName',
          component: 'BaseCheckboxGroup',
          span: 24,
          options: [],
          width: '100%',
        },
      ],
      // 表但验证
      formRules: {
        addressBookName: {
          required: true,
          message: '通讯录姓名不能为空',
          trigger: 'blur',
        },
        projectPointName: {
          required: true,
          message: '项目点不能为空',
          trigger: 'blur',
        },
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      checked: [],
      labelIdArr: []
    }
  },
  created () {
    EventBus.$on('currentTree', data => {
      this.searchMap.deptId = data.id
      this.searchMap.projectPointName = data.projectPointName
      this.searchMap.projectPointId = data.projectPointId
      this.initContactList()
    })
    this.initgetLabelList()
  },
  methods: {
    // 节点点击触发
    handleNodeClick (data) {
      this.searchMap.deptId = data.id
      this.searchMap.projectPointId = data.projectPointId
      this.searchMap.projectPointName = data.projectPointName
      this.initContactList();
    },
    // 重置表单数据
    resetForm () {
      this.formModel = {
        addressBookAccount: undefined,
        addressBookName: undefined,
        labelList: [],
        phonenumber: undefined,
        projectPointName: undefined,
        remark: undefined,
      };
    },
    // 加载数据
    initContactList () {
      this.loading = false
      getContactsList(this.searchMap).then(resp => {
        this.contactList = resp.rows
      })
    },
    // 加载角色列表
    initgetLabelList () {
      getLabelList().then(resp => {
        let tempArr = []
        for (const item of resp.rows) {
          tempArr.push({
            value: item.labelId,
            label: item.labelName
          })
        }
        this.formItemConfig[this.formItemConfig.findIndex(item => item.prop == 'labelList')].options = tempArr
        this.labelIdArr = tempArr
      })
    },
    // 根据部门ID查询用户
    initPersonnelOptions () {
      const params = {
        deptId: this.searchMap.deptId
      }
      listUser(params).then(resp => {
        // this.personnelOptions = resp.rows
        this.formItemConfig.forEach(item => {
          if (item.prop === 'userIdList') {
            const options = resp.rows.map(row => {
              return {
                value: row.userId,
                label: row.nickName
              }
            })
            this.$set(item, 'options', options)
          }
        })
      })
    },
    // 根据条件查询
    handleSearch () {
      this.searchMap.pageNum = 1
      this.initContactList()
    },
    //重置搜索栏数据
    handleReset () {
      this.$refs['searchMap'].resetFields()
      this.handleSearch()
    },
    // 修改数据
    async handleEdit (row) {
      this.title = "修改用户组信息"
      this.resetForm()
      const addressBookId = row.addressBookId
      await this.initPersonnelOptions()
      this.formItemConfig.forEach(item => {
        if (item.prop === 'userIdList') {
          this.$set(item, 'hidden', true)
        }
      })
      this.DialogVisibleUser = true
      getContactsId(addressBookId).then(response => {
        // 获取项目点名称
        if (response.data.projectPoint) {
          response.data.projectPointName = response.data.projectPoint.projectPointName
        }
        else {
          response.data.projectPointName = "无数据"
        }
        let templateList = []
        for (const item of response.data.labelList) {
          templateList.push(item.labelId)
        }
        response.data.labelList = templateList
        this.formModel = response.data
        console.log(response)
      });
    },
    // 新增用户信息
    async handleAdd () {
      this.title = " 新增用户组信息"
      this.resetForm()
      this.formItemConfig.forEach(item => {
        if (item.prop === 'userIdList') {
          this.$set(item, 'hidden', false)
        }
      })
      await this.initPersonnelOptions()
      this.formModel.projectPointName = this.searchMap.projectPointName
      this.DialogVisibleUser = true
    },
    // 新增标签
    tagAdd () {
      this.tableDialogVisible = true
    },
    getpostOptions () {
      this.formItemConfig.forEach(item => {
        if (item.prop === 'postIds') {
          item.options = this.postOptions
          item.filedLabel = 'postName'
          item.filedValue = 'postId'
        }
      })
    },
    //点击删除
    handleDelete (row) {
      const addressBookId = row.addressBookId
      this.$confirm("确认删除这行数据吗？", "提示", {
        configButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          delContacts([addressBookId]).then((response) => {
            this.initContactList()
          });
        })
        .catch(() => {
        });
    },
    submitFrom (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.formModel.addressBookId !== undefined) {
            if (this.formModel.labelList.length == 0) {
              this.formModel.labelIdList = [0]
            } else {
              this.formModel.labelIdList = this.formModel.labelList
            }
            updateContacts(this.formModel).then(response => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.DialogVisibleUser = false
              this.initContactList()
            })
          } else {
            this.formModel.projectPointId = this.searchMap.projectPointId
            this.formModel.labelIdList = this.formModel.labelList
            addContacts(this.formModel).then(response => {
              if (response.code === 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: response.msg,
                  type: "error",
                });
              }
              this.DialogVisibleUser = false
              this.initContactList()
            })
          }
        }
      })
    },
    // 标签管理弹窗关闭
    cancel () {
      this.tableDialogVisible = false
    },
  },
  computed: {
    pageTitle () {
      return '用户组管理'
    },
  },
  mounted () {
    // console.log(this.$refs.addUserFrom)
  },
  beforeDestroy: function () {
    EventBus.$off('currentTree');
  }
}
</script>
  
<style lang="less" scoped>
@import url("@/common/elementui.less");

.normal_dialog {
  background: url("@/assets/images/home/content.png") no-repeat;
}

.user_container {
  .user_main {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0;

    .user_content {
      display: flex;
      flex-direction: column;
      padding: 15px 20px;
      height: calc(100% - 70px);
      background: url("@/assets/images/home/content.png") no-repeat;
      background-size: cover;
      .content_footer {
        text-align: right;
        height: 32px;
      }
    }
  }

  .dialog_content {
    padding: 5px;
  }
}

.flex-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-tag {
    color: rgb(142, 170, 190);
    margin-right: 5px;
  }
}

/deep/ .content {
  .el-checkbox__label {
    padding-left: 8px;
  }

  .checkbox-icon {
    font-family: "iconfontShuzhi" !important;
    font-size: 16px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    width: 16px;
    height: 16px;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #309eff;
    color: #309eff;
    font-size: small;
  }

  .el-checkbox:last-of-type {
    margin-right: 20px;
  }

  .el-checkbox {
    margin-right: 20px;
  }

  .checkbox-title {
    width: 56px;
    height: 20px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #309eff;
    line-height: 20px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    padding-left: 8px;
  }
}
</style>